<template>
  <div class="content-container">
    <div class="item-header">
      <div class="header-title">房源管理</div>
    </div>
    <div class="item-content" v-loading="contentLoading">
      <el-button type="primary" size="default" @click="addRoomInfo">新增房源信息</el-button>
      <el-form
        v-show="isShowSearchForm"
        class="search-form"
        :inline="true"
        :model="searchRoomForm"
        :rules="searchRoomFormRules"
        ref="searchRoomFormRef"
        label-position="right"
        label-width="auto"
        >
        <el-form-item label="房源名称" prop="roomName">
          <el-input v-model.trim="searchRoomForm.roomName" placeholder="请输入房源名称" clearable/>
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="searchRoomForm.city" placeholder="请选择" clearable>
            <el-option v-for="item in cityList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="房源类型" prop="roomType">
          <el-select v-model="searchRoomForm.roomType" placeholder="请选择" clearable>
            <el-option v-for="item in roomTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="房东类型" prop="ownerType">
          <el-select v-model="searchRoomForm.ownerType" placeholder="请选择" clearable>
            <el-option v-for="item in ownerTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="dateTime"
            type="datetimerange"
            :shortcuts="shortcuts"
            :disabled-date="isDateDisable"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            unlink-panels
          />
        </el-form-item> -->
      </el-form>
      <div class="operation-btns">
        <el-button type="primary" @click="searchRoomList">查询</el-button>
        <el-button @click="resetSearchForm">重置</el-button>
        <el-button v-if="isShowSearchForm" type="primary" link @click="foldOperate"><el-icon class="el-icon--right"><ArrowUp /></el-icon>收起</el-button>
        <el-button v-else type="primary" link @click="foldOperate"><el-icon class="el-icon--right"><ArrowDown /></el-icon>展开</el-button>
      </div>
      <el-table
        :data="roomList"
        style="width: 100%; margin-top: 20px;"
        :default-sort="{ prop: 'color', order: 'descending' }"
        stripe
        >
        <el-table-column type="expand" show-overflow-tooltip>
          <template #default="props">
            <div>
              <p class="margin-left-20">地址: {{ props.row.address }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="房源名称" prop="roomName" show-overflow-tooltip/>
        <el-table-column label="房源类型" prop="roomType" width="80" show-overflow-tooltip/>
        <el-table-column label="城市" prop="city" width="80" show-overflow-tooltip/>
        <el-table-column label="房东ID" prop="ownerId" show-overflow-tooltip/>
        <el-table-column label="房东类型" prop="ownerType" width="80" show-overflow-tooltip/>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip/>
        <el-table-column label="推荐指数" prop="color" sortable width="190">
          <template #default="scope">
            <el-rate :colors="elRateColor" v-model="scope.row.color" disabled show-score text-color="#ff9900" score-template="{value} 分"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="editRoom(scope.row)">编辑</el-button>
            <el-button size="small" type="primary" link @click="deleteRoomConfirm(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <HPagination
        v-if="roomListPage.total > 0"
        :pageSize="roomListPage.pageSize"
        :currentPage="roomListPage.currentPage"
        :totalSize="roomListPage.total"
        :pageSizeList="[10, 20, 30, 50]"
        @selectPageSize="roomListSizeChange"
        @handleCurrentChange="roomListCurrentChange"
      >
      </HPagination>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { roomStore } from '@/stores'
import { roomTypeOptions, ownerTypeOptions, elRateColor } from '@/assets/js/enum'


const route = useRoute()
const router = useRouter()
const useRoomStore = roomStore()
const contentLoading = ref<boolean>(false)
const searchRoomFormRef = ref<any>(null)
const isShowSearchForm = ref(true)
const foldOperate = () => {
  isShowSearchForm.value = !isShowSearchForm.value
}
const cityList = reactive([
  {
    value: 'Beijing',
    label: '北京'
  },
  {
    value: 'Shanghai',
    label: '上海'
  },
  {
    value: 'Guangzhou',
    label: '广州'
  },
  {
    value: 'Shenzhen',
    label: '深圳'
  }
])
const searchRoomForm = reactive({
  roomName: '',
  city: '',
  roomType: '',
  ownerType: '',
  // createTime: [],
})
const searchRoomFormRules = reactive({
  roomName: [
    { required: false, message: '请输入房源名称', trigger: 'blur' }
  ],
  city: [
    { required: false, message: '请选择城市', trigger: 'blur' }
  ],
  createTime: [
    { required: false, message: '请选择创建时间', trigger: 'blur' }
  ]
})

  /**
   * 时间选择 start
   */
   const getRangeDateTime = (day: number) => {
    const endDate = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const startDate = dayjs().subtract(day, 'day').format('YYYY-MM-DD HH:mm:ss')
    return [startDate, endDate]
  }
  const shortcuts = [
    {
      text: '最近一周',
      value: () => {
        return getRangeDateTime(7)
      }
    },
    {
      text: '最近一个月',
      value: () => {
        return getRangeDateTime(30)
      }
    },
    {
      text: '最近三个月',
      value: () => {
        return getRangeDateTime(90)
      }
    }
  ]
  const range = getRangeDateTime(100)
  const dateTime = ref<any>(range)
  const isDateDisable = (date: any) => {
    return date.getTime() > dayjs()
  }
  /**
   * 时间选择 end
   */

  const roomList = ref<any>([
    {
      id: 1,
      roomName: '苏州天华小区一期2幢301',
      roomType: '整租',
      address: '江苏省苏州市区××××××××××××××××××××××××××',
      city: 'suzhou',
      ownerId: '4523132413',
      ownerType: '一房东',
      color: 1.5,
      remark: '备注1111'
    },
    {
      id: 2,
      roomName: '苏州天华小区一期2幢301',
      roomType: '整租',
      address: '江苏省苏州市区××××××××××××××××××××××××××',
      city: 'suzhou',
      ownerId: '4523132413',
      ownerType: '二房东',
      color: 5,
      remark: '备注1111'
    },
  ])

  // 分页
  const roomListPage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 1 //TODO: 后端返回
  })
  const roomListSizeChange = (val: number) => {
    roomListPage.currentPage = 1
    roomListPage.pageSize = val
    getRoomList()
  }
  const roomListCurrentChange = (val: number) => {
    roomListPage.currentPage = val
    getRoomList()
  }

  const editRoomId = ref<string>('')
  const addEditRoomDialogRef = ref<any>(null)

  // 查询
  const searchRoomList = () => {
    getRoomList()
  }

  // 重置
  const resetSearchForm = () => {
    searchRoomFormRef.value.resetFields()
    roomListPage.currentPage = 1
    roomListPage.pageSize = 10
    getRoomList()
  }

  // 新增信息
  const addRoomInfo = () => {
    editRoomId.value = ''
    router.push({
      name: 'addEditRoom'
    })
  }
  // 编辑信息
  const editRoom = (row: any) => {
    router.push({
      path: '/admin/roomManage/addEdit',
      query: {
        roomId: row.id
      }
    })
  }
  // 删除确认
  const deleteRoomConfirm = (row: any) => {
    ElMessageBox.confirm(
      '确定删除该条信息吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false,
        closeOnPressEscape: false
      }
    )
    .then(() => {
      deleteRoom(row)
    })
    .catch(() => {
    })
  }
  // 删除信息
  const deleteRoom = (row: object) => {
    const params = {
      // roomId: row.id
    }
    useRoomStore.deleteRoomInfo(params).then((res: any) => {
      if (res.state === 'OK') {
        ElMessage.success('删除成功')
        getRoomList()
      } else {
        ElMessage.error(res.errorMessage || '删除失败')
      }
    })
    .catch((err: any) => {
      ElMessage.error(err.errorMessage || '删除失败')
    })
  }
  // 获取房源列表
  const getRoomList = () => {
    contentLoading.value = true
    const params = {
      
    }
    useRoomStore.getAllRoomList(params).then((res: any) => {
      const { state, body } = res
      if (state === 'OK' && body) {
        roomList.value = body.content || []
        roomListPage.total = body.total || 0
      } else {
        ElMessage.error(res.errorMessage || '获取房源列表失败')
      }
    })
    .catch((err: any) => {
      ElMessage.error(err.errorMessage || '获取房源列表失败')
    })
    .finally(() => {
      contentLoading.value = false
    })
  }

  onMounted(() => {
    getRoomList()
  })

</script>

<style lang="scss" scoped>
.content-container {
  .item-content {
    .search-form {
      .el-input {
        width: 240px;
      }
      .el-select {
        width: 200px;
      }
    }
  }
}
:deep(.h-row) {
  .h-cell {
    background: #F4F5F7;
    .cell {
      border-left: 1px solid #FFFFFF;
      font-size: 12px;
      color: #333;
    }
    &:first-child {
      .cell {
        border-left: none;
      }
    }
  }
}
</style>
